package com.star.uc.infras.filter;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.util.ContentCachingRequestWrapper;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * 重复读取请求包装器
 *
 * @author zhouhengzhe
 */
public class RepeatReadRequestWrapper extends ContentCachingRequestWrapper {

    private boolean fistRead = true;

    public RepeatReadRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    public RepeatReadRequestWrapper(HttpServletRequest request, int contentCacheLimit) {
        super(request, contentCacheLimit);
    }

    /**
     * 设置字符集
     *
     * @return String 字符集
     */
    @NotNull
    @Override
    public String getCharacterEncoding() {
        return "UTF-8";
    }

    /**
     * 获取输入流
     *
     * @return ServletInputStream 输入流
     * @throws IOException
     */
    @NotNull
    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (fistRead) {
            fistRead = false;
            return super.getInputStream();
        } else {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(getContentAsByteArray());
            return new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return byteArrayInputStream.available() <= 0;
                }

                @Override
                public boolean isReady() {
                    return true;
                }

                /**
                 * 设置读监听器
                 * @param listener 监听器
                 */
                @Override
                public void setReadListener(ReadListener listener) {
                }

                @Override
                public int read() throws IOException {
                    return byteArrayInputStream.read();
                }
            };
        }
    }
}
